package koalacam.server;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;


import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;  


/**
 * 底库管理
 * @author Wangshutao
 * 2016年7月4日
 */
public class Subject {
	/**
	 * 获取所有用户列表
	 * @param cookieStore cookie值
	 * @param url 
	 * @throws Exception 
	 */
	public static List<Integer> mobileAdminSubjects(CookieStore cookieStore , String url ) throws Exception{
		System.out.println("Start GET /mobile-admin/subjects 获取所有用户列表 ...");

		//自定义HttpClients 设置CookieStore 
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpGet request = new HttpGet(url);
        
        CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONArray array = resp.getJSONArray("data");
        	List<Integer> ids = new ArrayList<Integer>();
        	for (int i = 0; i < array.length(); i++) {
				JSONObject userInfo = (JSONObject)array.get(i);
				Integer id = userInfo.getInt("id");
				ids.add(id);
				System.out.println("id:" + id + ",name:" + userInfo.getString("name"));
			}
        	return ids;
        }
        return null;
	}
	
	/**
	 * 创建用户
	 * @param cookieStore cookie值
	 * @param url
	 * @param subject_type 用户类型
	 * @param name 姓名
	 * @param photo_ids 识别头像列表
	 * @throws Exception 
	 */
	public static Integer subject(CookieStore cookieStore , String url,Integer subject_type, String name, List<Integer> photo_ids) throws Exception{
		System.out.println("Start POST /subject 创建用户 ...");
		
		//自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost request = new HttpPost(url);
        //设置Content-Type
        request.setHeader("Content-Type", "application/json");
        
        JSONObject json = new JSONObject();
        json.put("subject_type", subject_type);//如果subject_type不等于0，必须要指定start_time，end_time
        json.put("name", name);
        json.put("photo_ids", photo_ids);
        
//        String param = "{\"birthday\":0,\"gender\":0,\"subject_type\":0,\"purpose\":0,\"end_time\":0,\"title\":\"ma\",\"entry_date\":0,\"start_time\":0,"
//        		+ "\"phone\":\"13451325636\",\"name\":\"孙巍\",\"department\":\"研发中心\",\"email\":\"gift1985@191.com\"}";

        
        System.out.println(json.toString());
        request.setEntity(new StringEntity(json.toString(), "UTF-8"));
        
    	CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        System.out.println(responseBody);
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONObject userInfo = resp.getJSONObject("data");
        	System.out.println("id:"+ userInfo.getInt("id") + ",name:" + userInfo.getString("name"));
        	return userInfo.getInt("id");
        }
        return null;
	}

	
	/**
	 * 获取用户信息
	 * @param cookieStore
	 * @param url
	 */
	public static void getSubject(CookieStore cookieStore , String url) throws Exception{
		System.out.println("Start GET /subject/[id] 获取用户信息 ...");
		
		//自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpGet request = new HttpGet(url);
//        HttpPut request = new HttpPut(url);
        
        CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.err.println(responseBody);
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONObject userInfo = resp.getJSONObject("data");
        	System.out.println("id:" + userInfo.getInt("id") + ",name:"+ userInfo.getString("name"));	
        }
	}
	
	/**
	 * 更新用户信息
	 * @param cookieStore
	 * @param url /subject/[id]
	 * @param name 名字
	 */
	public static void updateSubject(CookieStore cookieStore , String url, String name) throws Exception{
		System.out.println("Start PUT /subject/[id] 更新用户信息 ...");
		
		//自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPut request = new HttpPut(url);
        //设置Content-Type
        request.setHeader("Content-Type", "application/json");
        
        JSONObject json = new JSONObject();
        json.put("name", name);
        
        request.setEntity(new StringEntity(json.toString(), "UTF-8"));
        
        CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONObject userInfo = resp.getJSONObject("data");
        	System.out.println("id:" + userInfo.getInt("id") + ",name:"+ userInfo.getString("name"));	
        }
	}
	
	/**
	 * 删除用户
	 * @param cookieStore cookie值
	 * @param url /subject/[id]
	 * @throws Exception
	 */
	public static void deleteSubject(CookieStore cookieStore , String url) throws Exception{
		System.out.println("Start DELETE /subject/[id] 删除用户 ...");
		
		//自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpDelete request = new HttpDelete(url);
        
        CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONObject userInfo = resp.getJSONObject("data");
        	System.out.println("id:" + userInfo.getInt("id") + ",name:"+ userInfo.getString("name"));	
        }
	}
	
	/**
	 * 上传识别照片
	 * @param photo 底库照片
	 * @param subject_id 用户id
	 * @return id 照片id
	 * @throws Exception
	 */
	public static Integer photo(CookieStore cookieStore , String url ,String photo, Integer subject_id) throws Exception {
        System.out.println("Start POST /subject/photo 上传识别照片 ...");
        System.out.println("photo:" + photo);
        
        //自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost request = new HttpPost(url);
        
        //设置底库照片 并关联到用户
        MultipartEntity reqEntity = new MultipartEntity();  
        reqEntity.addPart("photo", new FileBody(new File(photo)));
        if(null != subject_id){
        	reqEntity.addPart("subject_id", new StringBody(subject_id.toString()));
        }
        request.setEntity(reqEntity); 
        
    	CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
        	
            System.out.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	JSONObject data = resp.getJSONObject("data");
        	System.out.println("id:" + data.getInt("id") + "," + "quality:" + data.getDouble("quality") );
        	return data.getInt("id");
        }
        return null;
    }
	
	/**
	 * 上传显示头像
	 * @param photo 头像
	 * @param subject_id 关联用户id
	 * @throws Exception
	 */
	public static void avatar(CookieStore cookieStore , String url ,String photo,Integer subject_id) throws Exception {
        System.out.println("Start POST /subject/avatar 上传显示头像 ...");
        
        //自定义HttpClient 设置CookieStore
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
        HttpPost request = new HttpPost(url);
        
        //设置显示头像  并关联到用户
        MultipartEntity reqEntity = new MultipartEntity();  
        reqEntity.addPart("avatar", new FileBody(new File(photo)));
        reqEntity.addPart("subject_id", new StringBody(subject_id.toString()));
        request.setEntity(reqEntity); 
        
    	CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        
        //解析JSON数据
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result + ",desc:" + resp.getString("desc"));
        }else{
        	System.out.println("url:"+ resp.getJSONObject("data").getString("url"));	
        }
    }
	
	
}
